package com.wyh.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;

public class JWTUtil {
    private static final String KEY = "SDKltwTl3SiWX62dQiSHblEB6O03FG9/vEaivFu6c6g=";

    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(KEY));

    //过期时间
    private static final long EXPIRATION = 60*60*1000;
    public static String getToken(HashMap<String, Object> claim){
        return Jwts.builder()
                .setClaims(claim)//设置载荷
                .setIssuedAt(new Date(System.currentTimeMillis()))//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))//设置过期时间
                .signWith(SECRET_KEY)//设置签名算法
                .compact();//将头部，载荷，签名编码后拼接成字符串并返回
    }

    public static Claims parseToken(String token){
        JwtParserBuilder parserBuilder = Jwts.parserBuilder().setSigningKey(SECRET_KEY);
        return parserBuilder.build().parseClaimsJws(token).getBody();
    }
}
